/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jturbofile.net;

import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import jturbofile.gui.JTurboFileGUI;
import jturbofile.gui.LogPanel;

/**
 *
 * @author Rolf
 */
public class ConnectThread implements Runnable {

    private String addr;
    private int port;
    
    public ConnectThread(String addr, int port) {
        this.port = port;
        this.addr = addr;
    }
    
    public void run() {
        try {
            LogPanel.singleton().logln("Connecting to ["+addr+":"+port+"]...");
            
            Socket s = new Socket();
            SocketAddress sa = new InetSocketAddress(addr, port);
            
            s.connect(sa, 2000);
            
            if( s.isConnected() ) {
            
                if( s.getInetAddress().getHostAddress().equals(s.getLocalAddress().getHostAddress()) ) {
                    LogPanel.singleton().logln("Cant connect to self!");
                }
                else {
                    LogPanel.singleton().logln("Connection established ["+s.getInetAddress().getHostAddress()+"]...");

                    String key = NetCore.singleton().generateKey(s);

                    if( !NetCore.singleton().getPeers().containsKey(key) ) {
                        PeerThread pt = new PeerThread(s);
                        NetCore.singleton().getPeers().put(key, pt);
                        new Thread(pt).start();
                        
                        JTurboFileGUI.singleton().updateUsers();
                    }
                    else {
                        LogPanel.singleton().logln("Already connected to ["+s.getInetAddress().getHostAddress()+"]");
                    }
                }
            }
            else {
                LogPanel.singleton().logln("Unable to connect to ["+s.getInetAddress().getHostAddress()+"]");
            }
        }
        catch (Exception e) {
            LogPanel.singleton().logln("Error connecting to "+addr+" on port "+port+": "+e);
        }
    }
}
